import { Context } from 'koa';
import KoaRouter from 'koa-router';
import { validate } from '@/middleware/validate';
import Joi from 'joi';
import { CheckList } from '@/models/checkList';
import { Check } from '@/models/check';
import { CreateCheckRequest, UpdateCheckRequest } from '@/types/route';
import { v4 as uuidv4 } from 'uuid';
export default (router: KoaRouter) => {
    // 根据卡片ID获取CheckList和Checks
    router.get('/card/:cardId/checklist', async (ctx: Context) => {
        try {
            const { cardId } = ctx.params;
            const checkLists = await CheckList.find({ cardId }).sort({ createdAt: -1 });
            
            // 获取所有CheckList的checkListId
            const checkListIds = checkLists.map(checkList => checkList.checkListId);
            
            // 一次性查询所有相关的Checks
            const checks = await Check.find({ checkListId: { $in: checkListIds } }).sort({ createdAt: -1 });
            
            // 将Checks映射到对应的CheckList，并移除_id和__v
            const checkListsWithChecks = checkLists.map(checkList => ({
                ...checkList.toObject({ virtuals: false, getters: true }),
                checks: checks
                    .filter(check => check.checkListId === checkList.checkListId)
                    .map(check => {
                        const checkObj = check.toObject({ virtuals: false, getters: true });
                        return checkObj;
                    })
            }));

            ctx.setResponse(checkListsWithChecks, '获取成功');
        } catch {
            ctx.status = 500;
            ctx.setResponse(null, '获取失败', 500);
        }
    });
    // 新增 Check
    router.post('/checklist/:checkListId/check', 
        validate(Joi.object({
            title: Joi.string().required().min(1).max(50).messages({
                'string.empty': '标题不能为空',
                'string.min': '标题不能为空',
                'string.max': '标题长度不能超过50个字符',
                'any.required': '标题是必填项'
            })
        })), 
        async (ctx: Context) => {
            try {
                const { checkListId } = ctx.params;
                const { title } = ctx.request.body as CreateCheckRequest;

                // 验证 CheckList 是否存在
                const checkList = await CheckList.findOne({ checkListId });
                if (!checkList) {
                    ctx.status = 404;
                    return ctx.setResponse(null, 'CheckList不存在', 404);
                }

                // 创建新的 Check
                const newCheck = await Check.create({
                    checkId: uuidv4(),
                    checkListId,
                    title,
                    completed: false,
                    createdAt: Date.now(),
                    updatedAt: Date.now()
                });

                ctx.setResponse(newCheck, '创建成功');
            } catch {
                ctx.status = 500;
                ctx.setResponse(null, '创建失败', 500);
            }
        }
    );
    // 修改 Check 的勾选状态和标题
    router.put('/check/:checkId', 
        validate(Joi.object({
            title: Joi.string().min(1).max(50).messages({
                'string.empty': '标题不能为空',
                'string.min': '标题不能为空',
                'string.max': '标题长度不能超过50个字符'
            }),
            completed: Joi.boolean()
        })), 
        async (ctx: Context) => {
            try {
                const { checkId } = ctx.params;
                const { title, completed } = ctx.request.body as UpdateCheckRequest;

                const updateData: { 
                    title?: string; 
                    completed?: boolean; 
                    completedAt?: number; 
                    updatedAt: number 
                } = {
                    updatedAt: Date.now()
                };

                if (title) updateData.title = title;
                
                if (typeof completed === 'boolean') {
                    updateData.completed = completed;
                    updateData.completedAt = completed ? Date.now() : undefined;
                }

                const updatedCheck = await Check.findOneAndUpdate(
                    { checkId },
                    updateData,
                    { 
                        new: true,
                        projection: { _id: 0, __v: 0 }
                    }
                );

                if (!updatedCheck) {
                    ctx.status = 404;
                    return ctx.setResponse(null, 'Check不存在', 404);
                }

                ctx.setResponse(updatedCheck, '更新成功');
            } catch {
                ctx.status = 500;
                ctx.setResponse(null, '更新失败', 500);
            }
        }
    );
    // 删除 Check
    router.delete('/check/:checkId', async (ctx: Context) => {
        try {
            const { checkId } = ctx.params;

            // 查找 Check 是否存在
            const check = await Check.findOne({ checkId });
            if (!check) {
                ctx.status = 404;
                return ctx.setResponse(null, 'Check不存在', 404);
            }

            // 删除 Check
            await Check.deleteOne({ checkId });

            ctx.setResponse(null, '删除成功');
        } catch {
            ctx.status = 500;
            ctx.setResponse(null, '删除失败', 500);
        }
    });
};
